# -*- coding: utf-8 -*-
# @Time : 2021/12/9 16:17
# @Author : Limusen
# @File : request_demo_08

import re
import json
import jsonpath
import requests
from common.config_utils import local_config


class RequestsUtils:

    def __init__(self):
        # 封装好的配置文件直接拿来用
        self.hosts = local_config.get_hosts
        # 全局session调用
        self.session = requests.session()
        # 临时变量存储正则或者jsonpath取到的值
        self.temp_variables = {}

    def __get(self, request_info):
        """
        get请求封装
        :param request_info:
        :return:
        """
        # 　request_info 是我们封装好的数据，可以直接拿来用
        url = "https://%s%s" % (self.hosts, request_info["请求地址"])
        variables_list = re.findall('\\${.+?}', request_info["请求参数(get)"])
        for variable in variables_list:
            request_info["请求参数(get)"] = request_info["请求参数(get)"].replace(variable, self.temp_variables[variable[2:-1]])

        response = self.session.get(url=url,
                                    params=json.loads(request_info["请求参数(get)"]),
                                    # params=json.loads(
                                    #     requests_info['请求参数(get)'] if requests_info['请求参数(get)'] else None),
                                    headers=json.loads(request_info["请求头部信息"]) if request_info["请求头部信息"] else None
                                    )
        if request_info["取值方式"] == "正则取值":
            value = re.findall(request_info["取值代码"], response.text)[0]
            self.temp_variables[request_info["取值变量"]] = value
        elif request_info["取值方式"] == "jsonpath取值":
            value = jsonpath.jsonpath(response.json(), request_info["取值代码"])[0]
            self.temp_variables[request_info["取值变量"]] = value

        result = {
            "code": 0,
            "response_code": response.status_code,
            "response_reason": response.reason,
            "response_headers": response.headers,
            "response_body": response.text
        }
        return result

    def __post(self, request_info):
        """
        post请求封装
        :param request_info:
        :return:
        """
        url = "https://%s%s" % (self.hosts, request_info["请求地址"])
        variables_list = re.findall('\\${.+?}', request_info["请求参数(get)"])
        for variable in variables_list:
            request_info["请求参数(get)"] = request_info["请求参数(get)"].replace(variable, self.temp_variables[variable[2:-1]])

        variables_list = re.findall('\\${.+?}', request_info["请求参数(post)"])
        for variable in variables_list:
            request_info["请求参数(post)"] = request_info["请求参数(post)"].replace(variable,
                                                                            self.temp_variables[variable[2:-1]])
        response = self.session.post(url=url,
                                     params=json.loads(request_info['请求参数(get)']),
                                     # params=json.loads(
                                     #     requests_info['请求参数(get)'] if requests_info['请求参数(get)'] else None),
                                     headers=json.loads(request_info["请求头部信息"]) if request_info["请求头部信息"] else None,
                                     json=json.loads(request_info["请求参数(post)"])
                                     )
        if request_info["取值方式"] == "正则取值":
            value = re.findall(request_info["取值代码"], response.text)[0]
            self.temp_variables[request_info["取值变量"]] = value
        elif request_info["取值方式"] == "jsonpath取值":
            value = jsonpath.jsonpath(response.json(), request_info["取值代码"])[0]
            self.temp_variables[request_info["取值变量"]] = value

        result = {
            "code": 0,
            "response_code": response.status_code,
            "response_reason": response.reason,
            "response_headers": response.headers,
            "response_body": response.text
        }
        return result

    def request(self, request_info):
        """
        封装方法自动执行post或者get方法
        :param request_info:
        :return:
        """
        request_type = request_info['请求方式']
        if request_type == "get":
            # 私有化方法,其他类均不可调用
            result = self.__get(request_info)
        elif request_type == "post":
            result = self.__post(request_info)
        else:
            result = {"code": 1, "error_message": "当前请求方式暂不支持!"}
        return result

    def request_steps(self, request_steps):
        """
        按照列表测试用例顺序执行测试用例
        :param request_steps:
        :return:
        """
        for request in request_steps:
            result = self.request(request)
            if result['code'] != 0:
                break
        return result


if __name__ == '__main__':
    requests_info = [
        {'测试用例编号': 'api_case_03', '测试用例名称': '删除标签接口测试', '用例执行': '是', '用例步骤': 'step_01', '接口名称': '获取access_token接口',
         '请求方式': 'get', '请求头部信息': '', '请求地址': '/cgi-bin/token',
         '请求参数(get)': '{"grant_type":"client_credential","appid":"wxb637f897f0bf1f0d","secret":"501123d2d367b109a5cb9a9011d0f084"}',
         '请求参数(post)': '', '取值方式': 'jsonpath取值', '取值代码': '$.access_token', '取值变量': 'token_value', '断言类型': 'json_key',
         '期望结果': 'access_token,expires_in'},
        {'测试用例编号': 'api_case_03', '测试用例名称': '删除标签接口测试', '用例执行': '是', '用例步骤': 'step_02', '接口名称': '创建标签接口',
         '请求方式': 'post', '请求头部信息': '', '请求地址': '/cgi-bin/tags/create', '请求参数(get)': '{"access_token":"${token_value}"}',
         '请求参数(post)': '{   "tag" : {     "name" : "asssqwe" } } ', '取值方式': '无', '取值代码': '"id":(.+?),',
         '取值变量': 'tag_id', '断言类型': 'none', '期望结果': ''}
    ]

    res = RequestsUtils()
    print(res.request_steps(requests_info))
